<?php

// +----------------------------------------------------------------------
// | MyCentOS
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://www.mycentos.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 琥珀 <317559272@qqq.com><http://www.mycentos.com>
// +----------------------------------------------------------------------
// | @date  : 2015-03-05 14:13:54
// +----------------------------------------------------------------------
// | @Last Modified by:  琥珀
// +----------------------------------------------------------------------
// | @Last Modified time: 2015-03-14 15:30:04
// +-----------------------------------------------------------------------


/**
 * 权限管理控制器
 * @authors 琥珀 (317559272@qq.com)
 */
namespace Admin\Controller;
use Think\Controller;
use Admin\Model\AuthRuleModel;
use Admin\Model\AuthGroupModel;
Class AuthController extends AdminController
{

    /**
     * 后台节点配置的url作为规则存入auth_rule
     * 执行新节点的插入,已有节点的更新,无效规则的删除三项任务
     */
    public function updateRules() {

        //需要新增的节点必然位于$nodes
        $nodes = M('Menu')->field('id,pid,name,url')->order('sort asc')->select();
        foreach ($nodes as $key => $value) {
            if (stripos($value['url'], MODULE_NAME) !== 0) {
                $nodes[$key]['url'] = MODULE_NAME . '/' . $value['url'];
            }
        }
        $AuthRule = M('AuthRule');

        //需要更新和删除的节点必然位于$rules
        $rules = $AuthRule->order('name')->select();

        //构建insert数据
        $data = array();

        //保存需要插入和更新的新节点
        foreach ($nodes as $value) {
            $temp['name'] = $value['url'];
            $temp['title'] = $value['name'];
            $temp['status'] = 1;
            $data[strtolower($temp['name']) ] = $temp;

            //去除重复项

        }
        $update = array();

        //保存需要更新的节点
        $ids = array();

        //保存需要删除的节点的id
        foreach ($rules as $index => $rule) {
            $key = strtolower($rule['name']);
            if (isset($data[$key])) {

                //如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];

                //为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']] = $rule;
            } elseif ($rule['status'] == 1) {
                $ids[] = $rule['id'];
            }
        }
        if (count($update)) {
            foreach ($update as $k => $row) {
                if ($row != $diff[$row['id']]) {
                    $AuthRule->where(array('id' => $row['id']))->save($row);
                }
            }
        }
        if (count($ids)) {
            $AuthRule->where(array('id' => array('IN', implode(',', $ids))))->save(array('status' => - 1));

            //删除规则是否需要从每个用户组的访问授权表中移除该规则?

        }
        if (count($data)) {
            $AuthRule->addAll(array_values($data));
        }
        if ($AuthRule->getDbError()) {
            trace('[' . __METHOD__ . ']:' . $AuthRule->getDbError());
            return false;
        } else {
            return true;
        }
    }
    public function index() {
        $model = M('Auth_group');
        $searchname = I('searchname');
        if ($searchname) {
            $map['id|title|description'] = array(intval($searchname), array('like', '%' . $searchname . '%'), array('like', '%' . $searchname . '%'), '_multi' => true);
        }
        $list = $this->lists($model, $map);
        $this->assign('list', $list);
        $this->assign('searchname', $searchname);
        $this->display();
    }
    public function addGroup() {
        if (IS_POST) {
            $data = I('post.');
            $model = M('Auth_group');
            if (false === $model->create($data)) {
                $this->error($model->getError());
            }
            $rs = $model->add();
            if ($rs !== false) {
                $this->success('新增成功!');
            } else {
                $this->error('新增失败!');
            }
        } else {
            $this->display('');
        }
    }
    public function editGroup() {
        if (IS_POST) {
            $data = I('post.');
            $model = M('Auth_group');
            if (false === $model->create($data)) {
                $this->error($model->getError());
            }
            $rs = $model->save();
            if ($rs !== false) {
                $this->success('修改成功!');
            } else {
                $this->error('修改失败!');
            }
        } else {
            $id = I('id');
            if (empty($id)) {
                $this->error('参数错误');
            }
            $map['id'] = $id;
            $data = M('Auth_group')->where($map)->find();
            $this->assign('data', $data);
            $this->display();
        }
    }
    public function delGroup($ids = 0) {
        empty($ids) && $this->error('参数错误！');
        $ids = is_array($ids) ? implode(',', $ids) : $ids;
        $map['id'] = array('in', $ids);
        $res = M('Auth_group')->where($map)->delete();
        if ($res !== false) {
            $this->success('删除成功！');
        } else {
            $this->error('删除失败！');
        }
    }

    //访问授权控制
    public function access() {
        $this->updateRules();
        $id = I('id');
        $auth_group = M('AuthGroup')->where(array('status' => array('egt', '0'), 'id' => $id))->getfield('id,title,rules');
        $grouplist = explode(",", $auth_group[$id]['rules']);
        $list = M('Menu')->field('id,pid,name,url,rel,target')->order('id asc')->select();
        $main_rules = M('AuthRule')->where($map)->getField('name,id');
        foreach ($list as $key => $value) {
            if (stripos($value['url'], MODULE_NAME) !== 0) {
                $list[$key]['url'] = MODULE_NAME . '/' . $value['url'];
            }
        }
        $list = list_to_tree($list, $pk = 'id', $pid = 'pid', $child = 'operator', $root = 0);
        $this->assign('id', $id);
        $this->assign('list', $list);
        $this->assign('main_rules', $main_rules);
        $this->assign('grouplist', $grouplist);
        $this->assign('this_group', $auth_group[$id]);
        $this->display();
    }

    //用户组数据写入跟新
    public function writeGroup() {
        $data = I('post.');
        $data['rules'] = implode(',', $data['rules']);
        $AuthGroup = M('AuthGroup');
        $data = $AuthGroup->create($data);
        if ($data) {
            if (empty($data['id'])) {
                $r = $AuthGroup->add();
            } else {
                $r = $AuthGroup->save();
            }
            if ($r === false) {
                $this->error('操作失败' . $AuthGroup->getError());
            } else {
                $this->success('操作成功!');
            }
        } else {
            $this->error('操作失败' . $AuthGroup->getError());
        }
    }
    public function authGroup() {
        $uid = I('uid');
        $auth_groups = D('AuthGroup')->getGroups();
        $user_groups = AuthGroupModel::getUserGroup($uid);
        $ids = array();
        foreach ($user_groups as $value) {
            $ids[] = $value['group_id'];
        }
        foreach ($auth_groups as $key => $value) {
            if (in_array($value['id'], $ids)) {
                $auth_groups[$key]['selected'] = "checked";
            }
        }
        $realname = D('User')->getRealname($uid);
        $this->assign('realname', $realname);
        $this->assign('uid', $uid);
        $this->assign('auth_groups', $auth_groups);
        $this->assign('user_groups', $ids);
        $this->display();
    }

    //获取用户组用户
    public function user($group_id) {
        if (empty($group_id)) {
            $this->error('参数错误');
        }
        $auth_group = M('AuthGroup')->where(array('status' => array('egt', '0')))->getfield('id,id,title,rules');
        $prefix = C('DB_PREFIX');
        $l_table = $prefix . (AuthGroupModel::Admin);
        $r_table = $prefix . (AuthGroupModel::AUTH_GROUP_ACCESS);
        $model = M()->table($l_table . ' m')->join($r_table . ' a ON m.uid=a.uid');
        $_REQUEST = array();
        $list = $this->lists($model, array('a.group_id' => $group_id, 'm.status' => array('egt', 0)), 'm.uid asc', 'm.uid,m.username,m.login_times,m.realname,m.last_login_time,m.last_login_ip,m.status');
        $this->assign('list', $list);
        $this->assign('auth_group', $auth_group);
        $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);
        $this->display();
    }

    /**
     * 将用户添加到用户组,入参uid,group_id
     */
    public function addToGroup() {
        $uid = I('uid');
        $gid = I('group_id');
        if (empty($uid)) {
            $this->error('参数有误');
        }
        $AuthGroup = D('AuthGroup');
        if (is_numeric($uid)) {
            if (is_administrator($uid)) {
                $this->error('该用户为超级管理员');
            }
            if (!M('Admin')->where(array('uid' => $uid))->find()) {
                $this->error('用户不存在');
            }
        }
        if ($gid && !$AuthGroup->checkGroupId($gid)) {
            $this->error($AuthGroup->error);
        }
        if ($AuthGroup->addToGroup($uid, $gid)) {
            $this->success('操作成功');
        } else {
            $this->error($AuthGroup->getError());
        }
    }
    public function removeFromGroup() {
        $uid = I('uid');
        $gid = I('group_id');
        if ($uid == UID) {
            $this->error('不允许解除自身授权');
        }
        if (empty($uid) || empty($gid)) {
            $this->error('参数有误');
        }
        $AuthGroup = D('AuthGroup');
        if (!$AuthGroup->find($gid)) {
            $this->error('用户组不存在');
        }
        $AuthGroup = D('AuthGroup');
        if (!$AuthGroup->removeFromGroup($uid, $gid)) {
            $this->error('操作失败');
        } else {
            $this->success('操作成功');
        }
        $this->success('操作成功');
    }
}
?>